package com.example.seh.home;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ListView;
import android.widget.Toast;

import com.example.seh.MainActivity;
import com.example.seh.R;
import com.example.seh.constant.Constant;
import com.example.seh.home.secondhand.GoodsDetailActivity;
import com.example.seh.home.select.Bean;
import com.example.seh.home.select.SearchAdapter;
import com.example.seh.home.select.SearchView;
import com.example.seh.square.Post;
import com.google.gson.Gson;
import com.google.gson.JsonElement;
import com.google.gson.JsonParser;
import com.google.gson.reflect.TypeToken;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;

import butterknife.OnTextChanged;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

public class SelectActivity extends AppCompatActivity implements SearchView.SearchViewListener {
    /**
     * 搜索结果列表view
     */
    private ListView lvResults;

    /**
     * 搜索view
     */
    private SearchView searchView;


    /**
     * 热搜框列表adapter
     */
    private ArrayAdapter<String> hintAdapter;

    /**
     * 自动补全列表adapter
     */
    private ArrayAdapter<String> autoCompleteAdapter;

    /**
     * 搜索结果列表adapter
     */
    private SearchAdapter resultAdapter;

    /**
     * 搜索数据
     */
//    private List<Bean> dbData;

    /**
     * 热搜版数据
     */
    private List<String> hintData;

    /**
     * 搜索过程中自动补全数据
     */
    private List<String> autoCompleteData;

    /**
     * 搜索结果的数据
     */
    private List<Bean> resultData;

    /**
     * 默认提示框显示项的个数
     */
    private static int DEFAULT_HINT_SIZE = 6;

    /**
     * 提示框显示项的个数
     */
    private static int hintSize = DEFAULT_HINT_SIZE;

    /**
     * 设置提示框显示项的个数
     *
     * @param hintSize 提示框显示个数
     */
    public static void setHintSize(int hintSize) {
        SelectActivity.hintSize = hintSize;
    }

    private String searchText;
    private List<Bean> dbData;

    private Handler myHandler = new Handler(Looper.myLooper()) {
        @Override
        public void handleMessage(@NonNull Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 1:
                    autoCompleteAdapter.notifyDataSetChanged();
                    break;
            }
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.activity_select);
        initData();
        initViews();
    }

    /**
     * 初始化视图
     */
    private void initViews() {
        lvResults = findViewById(R.id.main_lv_search_results);
        searchView = findViewById(R.id.main_search_layout);
        //设置监听
        searchView.setSearchViewListener(this);
        //设置adapter
        //searchView.setTipsHintAdapter(hintAdapter);
        searchView.setAutoCompleteAdapter(autoCompleteAdapter);

        lvResults.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int position, long l) {

                Intent intent = new Intent(SelectActivity.this, GoodsDetailActivity.class);
                intent.putExtra("searchGoods",resultData.get(position));
                startActivity(intent);
            }
        });
    }

    /**
     * 初始化数据
     */
    private void initData() {
        //从数据库获取数据
        //getDbData(searchText);
        //初始化热搜版数据
        getHintData();
        //初始化自动补全数据
        getAutoCompleteData(null, null);
        //初始化搜索结果数据
        getResultData(null, null);


    }

//    /**
//     * 获取db 数据
//     */
//    private void getDbData(String text) {
//        int size = 100;
//        dbData = new ArrayList<>();
////        for (int i = 0; i < size; i++) {
////            dbData.add(new Bean(R.drawable.user_logo, "android开发必备技能" + (i + 1), "Android自定义view——自定义搜索view"));
////        }
//
//        OkHttpClient okHttpClient = new OkHttpClient();
//
//        Request request = new Request.Builder()
//                .get()
//                .url(Constant.SEARCH_SEND + "key=" + text)
//                .build();
//        Log.e("地址：",request.url().toString());
//        Call call = okHttpClient.newCall(request);
//        call.enqueue(new Callback() {
//            @Override
//            public void onFailure(Call call, IOException e) {
//                Log.e("okhttp", "获取数据失败");
//                e.printStackTrace();
//            }
//            @Override
//            public void onResponse(Call call, Response response) throws IOException {
//                String selectData = response.body().string();
//                Log.e("数据s：",selectData);
//                getDataFromJsonData(selectData);
//            }
//        });
//    }
//
//    public void getDataFromJsonData(String selectData) {
//        try {
//            dbData = new ArrayList<>();
//            JSONObject jsonObject = new JSONObject(selectData);
//            //String selectDataStr = jsonObject.getString("data");
//            String selectDataStr = jsonObject.getString("searchHits");
//
//            JSONArray jsonArray = new JSONArray(selectDataStr);
//            for (int i=0; i<jsonArray.length();i++){
//                JSONObject json = (JSONObject) jsonArray.get(i);
//                JSONObject content = json.getJSONObject("content");
//
//                Bean bean = new Bean();
//                bean.setIconId(R.drawable.user_logo);
//                bean.setTitle(content.getString("goodsName"));
//                bean.setContent(content.getString("goodsDesc"));
//                bean.setCategory(content.getString("goodsCategory"));
//                dbData.add(bean);
//            }
//
//
//        } catch (JSONException e) {
//            e.printStackTrace();
//        }
//        Message message = new Message();
//        message.what = 1;
//        myHandler.sendMessage(message);
//    }

    /**
     * 获取热搜版data 和adapter
     */
    private void getHintData() {
        hintData = new ArrayList<>(hintSize);
        for (int i = 1; i <= hintSize; i++) {
            hintData.add("热搜版" + i + "：搜索" + i);
        }
        hintAdapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1, hintData);
    }


    /**
     * 获取自动补全data 和adapter
     */
    private void getAutoCompleteData(String text, List<Bean> data) {
        if (autoCompleteData == null) {
            // 初始化
            autoCompleteData = new ArrayList<>(hintSize);
        } else {
            // 根据text获取auto data
            autoCompleteData.clear();
            searchText = text;

            for (int i = 0, count = 0; i < data.size() && count < hintSize; i++) {
                //if (data.get(i).getTitle().contains(text.trim()) || data.get(i).getCategory().contains(text.trim())) {
                autoCompleteData.add(data.get(i).getTitle());
                count++;
                //}
            }
        }

        if (autoCompleteAdapter == null) {
            autoCompleteAdapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1, autoCompleteData);

        } else {
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    autoCompleteAdapter.notifyDataSetChanged();

                }
            });

        }

    }


    /**
     * 获取搜索结果data和adapter
     */
    private void getResultData(String text, List<Bean> dbData) {
        if (resultData == null) {
            // 初始化
            resultData = new ArrayList<>();
            Log.e("第一次点击item",resultData.toString());
        } else {
            resultData.clear();
            for (int i = 0; i < dbData.size(); i++) {
                //if (dbData.get(i).getTitle().contains(text.trim()) || dbData.get(i).getCategory().contains(text.trim())) {
                    resultData.add(dbData.get(i));
                //}
                Log.e("resultData",resultData.toString());
            }
        }
        if (resultAdapter == null) {
            resultAdapter = new SearchAdapter(this, resultData, R.layout.item_bean_list);
        } else {
            resultAdapter.notifyDataSetChanged();
        }
    }

    /**
     * 当搜索框 文本改变时 触发的回调 ,更新自动补全数据
     *
     * @param text
     */

    public void onRefreshAutoComplete(String text, List<Bean> beans) {
        //更新数据
        getAutoCompleteData(text, beans);
    }

    /**
     * 点击搜索键时edit text触发的回调
     *
     * @param text
     */
    public void onSearch(String text, List<Bean> beans) {
        //更新result数据
        getResultData(text, beans);
        lvResults.setVisibility(View.VISIBLE);
        //第一次获取结果 还未配置适配器
        if (lvResults.getAdapter() == null) {
            //获取搜索数据 设置适配器
            lvResults.setAdapter(resultAdapter);
        } else {
            //更新搜索数据
            resultAdapter.notifyDataSetChanged();
        }
        Toast.makeText(this, "完成搜素", Toast.LENGTH_SHORT).show();

    }


    @Override
    public void onTipsItemClick(String text) {

    }


}